//
//  SNPlanListViewController.m
//  ZhuoxinAgriculture
//
//  Created by stone on 16/12/24.
//  Copyright © 2016年 stone. All rights reserved.
//


#import "SNProductionPlanListModel.h"
#import "SNCompilePlanViewController.h"
#import "SNPlanListCell.h"
#import "Masonry.h"
#import "SNNMPlanListViewController.h"
#import "SNPlanListTopView.h"

//=************************ stone ***
@interface SNNMPlanListViewController ()<UITableViewDataSource,UITableViewDelegate>
/** tableView */
@property (nonatomic,weak) UITableView * tableView;
/** View */
@property (weak, nonatomic) SNPlanListTopView * planListTopView;

/** SNProductionPlanListModel */
@property (nonatomic,strong) SNProductionPlanListModel * productionPlanListModel;

/** firstLoad */
@property (nonatomic, assign,getter=isFirstLoad) BOOL firstLoad;
/** View */
@property (weak, nonatomic) UIImageView * emptyImageView;
@end

static SNProductionPlanListModel * __productionPlanListModel;
static SNPlantingDecisionMakerResult * __plantingDecisionMakerResult;

@implementation SNNMPlanListViewController
+ (SNPlantingDecisionMakerResult *)getPlantingDecisionMakerResult{
    return __plantingDecisionMakerResult;
}
+ (void)setPlantingDecisionMakerResult:(SNPlantingDecisionMakerResult *)plantingDecisionMakerResult{
    
    __plantingDecisionMakerResult = plantingDecisionMakerResult;
}
+ (SNProductionPlanListModel *)getProductionPlanListModel{
    return __productionPlanListModel;
}
+ (void)setProductionPlanListModel:(SNProductionPlanListModel *)productionPlanListModel{
    
    __productionPlanListModel = productionPlanListModel;
}
//===================================== stone ===========/
- (void)filterData:(SNProductionPlanListModel *)model
{
  NSMutableArray<SNProductionPlanListModel *> * arrM =   model.result.mutableCopy;
    
    for(int i = 0; i < arrM.count; i++) {
        if (arrM[i].status.integerValue > 2) {
            [arrM removeObjectAtIndex:i];
            i--;
        }
    }
    model.result = arrM.mutableCopy;

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.isFirstLoad) {
        self.firstLoad = NO;
    }else{
        
        
        NSString * searchText = self.year;
        
        NSString * RegExString = @"\\d{4}";
        
        NSRange range = [searchText rangeOfString:RegExString options:NSRegularExpressionSearch];
        
        NSString * year = [searchText substringWithRange:range];
        
        [[ZXHTTPManager sharedManager]viewplantplanWithCustNo:self.plantingDecisionMakerResult.custNo status:nil year:year completed:^(NSDictionary *jsonDict, NSError *error) {
            if (error) {
                NSLog(@"error = %@",error);
                HUDNormal(@"请检查您的网络");
                return ;
            }
            NSLog(@"jsonDict = %@",jsonDict);
            
            SNProductionPlanListModel * productionPlanListModel = [SNProductionPlanListModel mj_objectWithKeyValues:jsonDict];
            __productionPlanListModel = productionPlanListModel;
            [self filterData:productionPlanListModel];
            self.productionPlanListModel = __productionPlanListModel;
//            [productionPlanListModel.result enumerateObjectsUsingBlock:^(SNProductionPlanListResult * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                obj.status = @"2";
//            }];
            if (productionPlanListModel.result.count > 0) {
                self.empty = NO;
                [self.emptyImageView removeFromSuperview];
            }else{
                self.empty = YES;
                [self addEmptyView];
            }
            
            [self.tableView reloadData];
        }];
        
        
        
        //        self.productionPlanListModel = __productionPlanListModel;
        //        [self.tableView reloadData];
    }
    
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.firstLoad = YES;
    self.navigationItem.title = @"生产计划清单";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = kNormalBackgroundColor;
    // Do any additional setup after loading the view, typically from a nib.
    [SNUtils configNavigationStyleWithViewController:self];
    
    __plantingDecisionMakerResult = self.plantingDecisionMakerResult;
    
    [self addTopView];
    [self.view layoutIfNeeded];
    [self addTableView];
    
    /** 主线程 会先走... */
    if (self.isEmpty) {
        
        [self addEmptyView];
        
    }else{
        [self.emptyImageView removeFromSuperview];
    }
    
}
- (void)addEmptyView
{
    // self.view.layer.contents = (__bridge id)[UIImage imageNamed:@"icon_empty_view"].CGImage;
    self.view.backgroundColor = kNormalBackgroundColor;
    
    UIImageView * emptyImageView = ({
        UIImageView * imageView = [[UIImageView alloc] init];
        UIImage * image = [UIImage imageNamed:@"icon_empty_view"];
        imageView.image = image;
        
        imageView.frame = CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64);
        [self.view addSubview:imageView];
        
        
        
        imageView;
    });
    self.emptyImageView = emptyImageView;
    NSString * title = @"";
    NSString * message = @"未查到数据!";
    NSString * actionButtonTitle = @"确定";
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction * action = [UIAlertAction actionWithTitle:actionButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 确定之后需要 处理的code
        
    }];
    
    [alertController addAction:action];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)addTableView
{
    /** y坐标 */
    CGFloat y = CGRectGetMaxY(self.planListTopView.frame);
    /** 高度 tableView */
    CGFloat height = self.view.bounds.size.height - y;
    /** 样式 tableView */
    UITableViewStyle tableViewStyle = UITableViewStyleGrouped;
    
    CGRect frame = CGRectMake(0, y, self.view.bounds.size.width, height);
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:frame style:tableViewStyle];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = kNormalBackgroundColor;
    
    [self setupInit:tableView];
    
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //    tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    //    tableView.separatorColor = [UIColor greenColor];
    [self.view addSubview:tableView];
    
    [self addObserver];
    [self addRequest];
}
- (void)addTopView
{
    SNPlanListTopView * planListTopView = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([SNPlanListTopView class]) owner:nil options:nil] lastObject];
    self.planListTopView = planListTopView;
    
    [planListTopView configWithModel:self.plantingDecisionMakerResult year:self.year];
    
    [self.view addSubview:planListTopView];
    
    [planListTopView mas_makeConstraints:^(MASConstraintMaker * make) {
        make.left.mas_equalTo(self.view.mas_left).offset(12);
        make.right.mas_equalTo(self.view.mas_right).offset(-12);
        make.top.mas_equalTo(self.view.mas_top).offset(64);
    }];
}

//sn_note:=========  ============================ stone 🐳 ===========/
#pragma mark - <addRequest>
- (void)addRequest {
    // addRequest
    //    NSString *custNo = kUserInfo.account;
    //    custNo = @"15697480136";
    
    NSString * searchText = self.year;
    
    NSString * RegExString = @"\\d{4}";
    
    NSRange range = [searchText rangeOfString:RegExString options:NSRegularExpressionSearch];
    
    NSString * year = [searchText substringWithRange:range];
    
    [[ZXHTTPManager sharedManager]viewplantplanWithCustNo:kUserDetailInfo.custNo status:nil year:year completed:^(NSDictionary *jsonDict, NSError *error) {
        if (error) {
            NSLog(@"error = %@",error);
            HUDNormal(@"请检查您的网络");
            return ;
        }
        NSLog(@"jsonDict = %@",jsonDict);
        
        SNProductionPlanListModel * productionPlanListModel = [SNProductionPlanListModel mj_objectWithKeyValues:jsonDict];
        __productionPlanListModel = productionPlanListModel;
        self.productionPlanListModel = __productionPlanListModel;
        [self filterData:productionPlanListModel];
        
//        [productionPlanListModel.result enumerateObjectsUsingBlock:^(SNProductionPlanListResult * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            obj.status = @"2";
//        }];
        
        if (productionPlanListModel.result.count > 0) {
            self.empty = NO;
            [self.emptyImageView removeFromSuperview];
        }else{
            self.empty = YES;
            [self addEmptyView];
        }
        
        [self.tableView reloadData];
    }];
    
}
- (void)receivedTopViewUpdateYearNotification:(NSNotification *)notify
{
    //TODO: 做请求
    NSString * searchText = self.planListTopView.planNameLable.text;
    self.year = searchText;
    NSString * RegExString = @"\\d{4}";
    
    NSRange range = [searchText rangeOfString:RegExString options:NSRegularExpressionSearch];
    
    NSString * year = [searchText substringWithRange:range];
    NSLog(@"year = %@",year);
    [[ZXHTTPManager sharedManager]viewplantplanWithCustNo:self.plantingDecisionMakerResult.custNo status:nil year:year completed:^(NSDictionary *jsonDict, NSError *error) {
        if (error) {
            NSLog(@"error = %@",error);
            HUDNormal(@"请检查您的网络");
            return ;
        }
        NSLog(@"jsonDict = %@",jsonDict);
        
        SNProductionPlanListModel * productionPlanListModel = [SNProductionPlanListModel mj_objectWithKeyValues:jsonDict];
        self.productionPlanListModel = productionPlanListModel;
        [self filterData:productionPlanListModel];
        if (productionPlanListModel.result.count > 0) {
            self.empty = NO;
            [self.emptyImageView removeFromSuperview];
        }else{
            self.empty = YES;
            [self addEmptyView];
        }
        [self.tableView reloadData];
    }];
    
}
#pragma mark - <addObserver>
- (void)addObserver {
    // addObserver
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedTopViewUpdateYearNotification:) name:@"TopViewUpdateYearNotification" object:nil];
    
}
- (void)dealloc {
    NSLog(@"%@ %s %@",[self class], __func__ , @"im dying");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/** 初始化 tableView */
- (void)setupInit:(UITableView *)tableView
{
    //MARK: - 设置tableHeaderView
    //    {
    //        UIView * tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    //        tableView.tableHeaderView = tableHeaderView;
    //    }
    
    //MARK: - 注册
    {
        /** xib 注册cell */
        registerForCellFromeNib(tableView,SNPlanListCell);
        /** class 注册cell */
        //        registerForCellFromeClass(tableView,SNPlanListCell);
        
        /** xib 注册 headerSection */
        //    registerForHeaderFooterViewFromeNib(tableView,UITableViewHeaderFooterView);
        /** class 注册 headerSection */
        //    registerForHeaderFooterViewFromeClass(tableView,UITableViewHeaderFooterView);
        
        /** xib 注册 footerSection */
        //    registerForHeaderFooterViewFromeNib(tableView,UITableViewHeaderFooterView);
        /** class 注册 footerSection */
        //    registerForHeaderFooterViewFromeClass(tableView,UITableViewHeaderFooterView);
    }
    //MARK: - 设置高度
    {
        /** header */
        tableView.sectionHeaderHeight = 10;
        // tableView.estimatedSectionHeaderHeight = 100;
        // tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
        /** cell */
        tableView.estimatedRowHeight = 100;
        tableView.rowHeight = UITableViewAutomaticDimension;
        /** footer */
        tableView.sectionFooterHeight = 0.001;
        // tableView.estimatedSectionFooterHeight = 100;
        // tableView.sectionFooterHeight = UITableViewAutomaticDimension;
    }
}

#pragma mark - <UITableViewDataSource>
/** 组数 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSLog(@"self.productionPlanListModel.result.count = %ld",self.productionPlanListModel.result.count);
    NSLog(@"self.productionPlanListModel.result.count = %ld",self.productionPlanListModel.result.count);
    NSLog(@"self.productionPlanListModel.result.count = %ld",self.productionPlanListModel.result.count);
    NSLog(@"self.productionPlanListModel.result.count = %ld",self.productionPlanListModel.result.count);
    NSLog(@"self.productionPlanListModel.result.count = %ld",self.productionPlanListModel.result.count);
    NSLog(@"self.productionPlanListModel.result.count = %ld",self.productionPlanListModel.result.count);
    NSLog(@"self.productionPlanListModel.result.count = %ld",self.productionPlanListModel.result.count);
    return self.productionPlanListModel.result.count;
}
/** 行数 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
//MARK: -
//MARK: - cell
/** cell */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SNPlanListCell * cell = DequeueForCell(SNPlanListCell);
    //    SNTableViewCell * cell = [SNTableViewCell cellWithTableView:tableView];
    [cell setReloadDataOfTableView:^{
        
        NSString * searchText = self.year;
        
        NSString * RegExString = @"\\d{4}";
        
        NSRange range = [searchText rangeOfString:RegExString options:NSRegularExpressionSearch];
        
        NSString * year = [searchText substringWithRange:range];
        
        [[ZXHTTPManager sharedManager]viewplantplanWithCustNo:self.plantingDecisionMakerResult.custNo status:nil year:year completed:^(NSDictionary *jsonDict, NSError *error) {
            if (error) {
                NSLog(@"error = %@",error);
                HUDNormal(@"请检查您的网络");
                return ;
            }
            NSLog(@"jsonDict = %@",jsonDict);
            
            SNProductionPlanListModel * productionPlanListModel = [SNProductionPlanListModel mj_objectWithKeyValues:jsonDict];
            __productionPlanListModel = productionPlanListModel;
            self.productionPlanListModel = __productionPlanListModel;
            [self filterData:productionPlanListModel];
            
            [self.tableView reloadData];
        }];
        
        
        
        // [tableView reloadData];
        
    }];
    SNProductionPlanListResult * productionPlanListResult = self.productionPlanListModel.result[indexPath.section];
    NSLog(@"%@ | productionPlanListResult = %p",self.class,productionPlanListResult);
    cell.productionPlanListResult = productionPlanListResult;
    
    cell.viewController = self;
    cell.indexPath = indexPath;
    cell.plantingDecisionMakerResult = self.plantingDecisionMakerResult;
    //    cell.contentView.backgroundColor = indexPath.section % 2 == 0 ? [UIColor colorWithRed:247 / 255.0 green:206 / 255.0 blue:166 / 255.0 alpha:1.0] : [UIColor colorWithRed:242 / 255.0 green:154 / 255.0 blue:76 / 255.0 alpha:1.0];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    return cell;
}
#pragma mark - <UITableViewDelegate>
/** 自定义section header */
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UITableViewHeaderFooterView * headerView = DequeueForHeaderFooterView(UITableViewHeaderFooterView);
    
    // SNHeaderView * headerView = [SNHeaderView headerViewWithTableView:tableView];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return tableView.sectionHeaderHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return tableView.sectionFooterHeight;
}
/** 选中一行 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s", __func__);
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
/** 取消 选中 */
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0) {
    NSLog(@"%s", __func__);
}

@end
